<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 添加角色按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>
    </el-card>
    <!-- 角色列表 -->
    <el-table :data="roleList" style="width: 100%" border>
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-row class="rowPadding" :class='["bdbottom", i1 === 0 ? "bdtop" : "", "vcenter"]' v-for="(item1,i1) in props.row.children" :key="item1.id">
          <!-- 渲染一级权限 -->
          <el-col :span='5'>
            <el-tag closable @close='removeRightById(props.row,item1.id)'>{{ item1.authName }}</el-tag>
            <i class="el-icon-caret-right"></i>
          </el-col>
          <!-- 渲染二级三级权限 -->
          <el-col :span="19">
            <el-row :class="[i2===0?'' : 'bdtop', 'vcenter']" v-for="(item2,i2) in item1.children" :key="item2.id">
            <!-- 渲染二级权限 -->
              <el-col :span="6">
                <el-tag closable @close='removeRightById(props.row,item2.id)' type="success">{{ item2.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="18">
                <el-tag disable-transitions closable type="warning" @close="removeRightById(props.row,item3.id)" v-for="(item3) in item2.children" :key="item3.id">{{item3.authName}}</el-tag>
              </el-col>
            </el-row>
          </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column type="index"></el-table-column>
      <el-table-column label="角色名称" prop="roleName"></el-table-column>
      <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
      <el-table-column label="操作" width="350">
        <template v-slot:default="slotProps">
          <el-button type="primary" size="mini" icon="el-icon-edit">编辑</el-button>
          <el-button type="danger"  size="mini" icon="el-icon-delete">删除</el-button>
          <el-button type="warning" size="mini" icon="el-icon-setting" @click='setRightDialogVisibleHandle(slotProps.row)'>分配权限</el-button>
        </template>
      </el-table-column>
    </el-table>
  <!--  -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
      @close="setRightDialogClosed">
      <!-- 树形控件 -->
      <el-tree ref="treeRights" :data="rightList" :props="treeProps" node-key='id' show-checkbox default-expand-all :default-checked-keys="defKeys"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      roleList: [],
      setRightDialogVisible: false,
      rightList: [],
      // 树形控件绑定的对象
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      // 默认选中的ID
      defKeys: [],
      // 当前即将分配权限的角色Id
      roleId: ''
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    // 获取权限列表
    async getRolesList() {
      // this.$http.get('roles').then(
      //   function(res) {
      //     console.log(res)
      //   },
      //   function(err) {
      //     return err
      //   }
      // )
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.roleList = res.data
      // console.log(this.roleList)
    },
    // 通过Id删除权限
    async removeRightById(role, rightid) {
      console.log(role)
      const res = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      console.log(res)
      if (res !== 'confirm') return this.$message.info('已取消删除')
      const { data: result } = await this.$http.delete(`roles/${role.id}/rights/${rightid}`)
      if (result.meta.status !== 200) return this.$message.info('删除失败')
      role.children = result.data
      this.$message.success('删除成功')
    },
    async setRightDialogVisibleHandle(props) {
      this.roleId = props.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('获取权限列表失败')
      this.rightList = res.data
      // 获取所用三级权限的id
      this.getLeafKeys(props, this.defKeys)
      this.setRightDialogVisible = true
    },
    // 通过递归方式 遍历出所有三级节点,获取到三级节点的所有id,并存入数组中
    getLeafKeys(node, arr) {
      // 判断是否为三级几点
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },
    // 监听分配权限对话框关闭时调用
    setRightDialogClosed() {
      // 在调用getLeafKeys 之前先清楚defKeys中的数据
      this.defKeys = []
    },
    // 点击分配权限
    async allotRights() {
      const roleIds = [...this.$refs.treeRights.getCheckedKeys(), ...this.$refs.treeRights.getHalfCheckedKeys()]
      // const roleIdsStr = roleIds.join(',')
      const roleIdsStr = roleIds.toString()
      // console.log(roleIdsStr)
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: roleIdsStr })
      if (res.meta.status !== 200) return this.$message.error('分配权限失败')
      this.getRolesList()
      this.$message.success('分配权限成功')
      this.setRightDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 5px;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.bdtop {
  border-top: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items : center;
}
</style>
